import uuid
from django.http import HttpRequest
from django.shortcuts import render

# Create your views here.
# 打开上传文件页面
import os

import time


def f_file_uploadpage(request:HttpRequest):
    return render(request,'app03_file/file_upload.html/')

# 实现文件上传
def f_file_fileupload(request):
    # 文件读取流
    v_file_in = request.FILES.get('fileupload',None)
    # 生产文件上传后的名字
    # 1、获取所上传文件的名字
    v_file_upload_name = v_file_in.name
    # 2、修改文件的名字
    v_file_upload_name_list = v_file_upload_name.split('.')
    # v_file_upload_name_target = v_file_upload_name+time.strftime('%H:%M:%S',time.localtime())
    v_file_upload_name_target = v_file_upload_name_list[0] + str(uuid.uuid1())+'.'+v_file_upload_name_list[1]
    # v_file_upload_name_target = v_file_upload_name_list[0] + time.strftime('%H:%M:%S',time.localtime()) + '.' + v_file_upload_name_list[1]
    v_file_upload_path = os.path.join(os.getcwd(),'static/upload/'+v_file_upload_name_target)
    # 文件写入
    with open(v_file_upload_path,'wb') as file_out:
        v_content =v_file_in.read(32)
        while v_content:
            file_out.write(v_content)
            v_content = v_file_in.read(32)
            pass
        pass
    # with open(v_file_upload_path,'wb') as file_out:
    #     for v_content in v_file_in.chunks(32) :
    #         file_out.write(v_content)
    #         pass
    #     pass

    v_date={'code':200,'info':'成功'}
    return render(request,'/app03_file/file_upload_result.html',v_date)

# 把文件读取流里的内容写到一个文件里
def file_file_in_write(v_file_in_element, block_size:int):
    # 生成上传文件的名字
    # 1、获取文件的名字
    v_file_upload_name = v_file_in_element.name
    # 2、修改文件的名字
    v_file_upload_name_list = v_file_upload_name.split('.')
    v_file_upload_name_target = v_file_upload_name_list[0]+'_'+str(uuid.uuid1())+'.'+v_file_upload_name_list[1]
    v_file_upload_name_path = os.path.join(os.getcwd(),'static/upload/'+v_file_upload_name_target+'')
    with open(v_file_upload_name_path,'wb') as file_out:
        for v_content in v_file_in_element.chunks(block_size) :
            file_out.write(v_content)
            pass
        # v_content = v_file_in_element.read(32)
        # while v_content:
        #     file_out.write(v_content)
        #     v_content=v_file_in_element.read(32)
        #     pass

        pass
    pass

# 实现多文件上传
def f_file_fileuploadmul(request):
    v_file_in_list=request.FILES.getlist('fileupload_mul',None)
    for v_file_in_element in v_file_in_list:
        file_file_in_write(v_file_in_element,32)
        pass
    v_date={'code':200,'info':'成功'}
    return render(request,'app03_file/file_upload_result.html/',v_date)